package com.yuebu.yuebubtlib;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;

import com.yuebu.yuebubtlib.util.BLELogUtil;

import java.util.List;
import java.util.UUID;

/**
 * 获取设备的serviceUUId得到服务对象 打开notify监听
 */
public class BlueWriteDescriptor {
    public BlueWriteDescriptor() {

    }

    public boolean writeDescriptor(BluetoothGatt gatt, String serviceUUid, String notifyUUid, String cccdDescriptor) {
        BluetoothGattService service = gatt.getService(UUID.fromString(serviceUUid));
        if (service == null) {
            BLELogUtil.i("BluetoothGattService==null");
            return false;
        }
        BluetoothGattCharacteristic notifyCharacteristic = service.getCharacteristic(UUID.fromString(notifyUUid));
        if (notifyCharacteristic == null) {
            BLELogUtil.i("notifyCharacteristic == null");
            return false;
        }

        if (!gatt.setCharacteristicNotification(notifyCharacteristic, true)) {
            BLELogUtil.i("setCharacteristicNotification == false");
            return false;
        }
        gatt.readCharacteristic(notifyCharacteristic);
        List<BluetoothGattDescriptor> descriptorList = notifyCharacteristic.getDescriptors();
        for (BluetoothGattDescriptor descriptor : descriptorList) {
            boolean b = descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
            if (b){
                gatt.writeDescriptor(descriptor);
            }
        }
        return true;
    }
}
